package com.example.noteshare;

import org.apache.commons.codec.binary.Base64;

import com.example.noteshare.Utilities.Constants;
import com.example.noteshare.Utilities.Repo;
import com.example.noteshare.asyncTasks.AsyncPost;
import com.example.noteshare.gson.AddFileResult;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class UploadPage extends Activity {
	File path;
	ArrayAdapter<String> arrayAdpt;
	final Context context = this;
	String fileSelected;
	String classTag;
	String professorTag;
	EditText classInput;
	EditText professorInput;
	
	private String encodeFileToBase64Binary(String fileName)
			throws IOException {
 
		File file = new File(fileName);
		byte[] bytes = loadFile(file);
		byte[] encoded = Base64.encodeBase64(bytes);
		String encodedString = new String(encoded);
 
		return encodedString;
	}
 
	private static byte[] loadFile(File file) throws IOException {
	    InputStream is = new FileInputStream(file);
 
	    long length = file.length();
	    if (length > Integer.MAX_VALUE) {
	        // File is too large
	    }
	    byte[] bytes = new byte[(int)length];
	    
	    int offset = 0;
	    int numRead = 0;
	    while (offset < bytes.length
	           && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
	        offset += numRead;
	    }
 
	    if (offset < bytes.length) {
	    	is.close();
	        throw new IOException("Could not completely read file "+file.getName());
	    }
 
	    is.close();
	    return bytes;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload_page);
		classInput = (EditText)this.findViewById(R.id.classInput);
		professorInput = (EditText)this.findViewById(R.id.professorInput);
		final ListView filesList = (ListView)findViewById(R.id.files_list);
		ArrayList<String> files  = new ArrayList<String>();
		arrayAdpt= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,files);
		filesList.setAdapter(arrayAdpt);
		arrayAdpt.setNotifyOnChange(true);
		
		FileNameAsyncTask myTask = new FileNameAsyncTask();
		myTask.execute();
		
		
		filesList.setOnItemClickListener(new AdapterView.OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
			{
				fileSelected =(String) parent.getItemAtPosition(pos); // name of file selected
		        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		 
					// set title
					alertDialogBuilder.setTitle("Upload");
		 
					// set dialog message
					alertDialogBuilder
						.setMessage("Upload Notes to NoteShare?")
						.setCancelable(false)
						.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int id) {
								// if this button is clicked (user says yes to uploading), start copying and uploading selected file
												
								// get user input for tags
								classTag = classInput.getText().toString(); 
								professorTag = professorInput.getText().toString(); 
								
										
								String sdPath = "mnt/sdcard/";	// path to sd card in emulator
								String sourcePath = sdPath + fileSelected;	// file selected from sd card directory
			
								
								try {
									String file = encodeFileToBase64Binary(sourcePath);
									
									Map<String, String> params = new HashMap<String, String>();
									params.put("fileName", fileSelected);
									params.put("file", file);
									params.put("userId", Repo.userId);
									params.put("class", classTag);
									params.put("professor", professorTag);
									params.put("privacy", "Public");
									
									AsyncPost async = new AsyncPost(Constants.serverIP + Constants.addFile, params);
									
									//get the results
									String result = "{}";
									try {
										result = async.execute().get();
									} catch (InterruptedException e) {
										e.printStackTrace();
									} catch (ExecutionException e) {
										e.printStackTrace();
									}
									
									//parse tje results
									Gson gson = new GsonBuilder().create();
									AddFileResult lr = gson.fromJson(result, AddFileResult.class);
									
									//see if login was successful
									Boolean successful;
									try{
										successful = Boolean.parseBoolean(lr.getSuccessful());
									}catch(Exception e){
										successful = false;
									}
									
									String message;
									if(successful){
										message = "File upload successful";
									}else{
										message = "File upload failed";
									}
									
									Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
									
									
								} catch (Exception e) {
									e.printStackTrace();
								}
								
							}
						  })
						.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int id) {
								// if this button is clicked, just close
								// the dialog box and do nothing
								dialog.cancel();
							}
						});
		 
						// create alert dialog
						AlertDialog alertDialog = alertDialogBuilder.create();
		 
						// show it
						alertDialog.show();

			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.upload_page, menu);
		return true;
	}

	public void copy(File src, File dst) throws IOException {
	    InputStream in = new FileInputStream(src);
	    OutputStream out = new FileOutputStream(dst);

	    // Transfer bytes from in to out
	    byte[] buf = new byte[1024];
	    int len;
	    while ((len = in.read(buf)) > 0) {
	        out.write(buf, 0, len);
	    }
	    in.close();
	    out.close();
	}
	
	public ArrayList<String> getFileNames(){
		String sdPath= "mnt/sdcard/";	// Path to sd card, under mnt folder
		List<String> results = new ArrayList<String>();
		File[] files2 = new File(sdPath).listFiles();	// get file names in specified directory
		
		for(File file : files2){
			if (file.isFile()) {
		        results.add(file.getName());	// add file names to List<String>
		    }
		}
		
		// Convert List<String> to ArrayList
		ArrayList<String> listOfFiles = new ArrayList<String>(results.size());
		listOfFiles.addAll(results);
		
		return listOfFiles;
	}
	
	public class FileNameAsyncTask extends AsyncTask<Void, Void, Void> {	
		ArrayList<String> files;
		
		@Override
		protected void onPostExecute(Void arg0) {
			arrayAdpt.clear();
			arrayAdpt.addAll(files);
			arrayAdpt.notifyDataSetChanged();			
		}
		
		@Override
		protected Void doInBackground(Void... arg0) {
			files = getFileNames();
			
			return null;			
		}

}
}
